package runner;

import org.testng.TestNG;
import runner.ui.Data;
import runner.ui.Window;
import tests.FirstTestClass;
import tests.SecondTestClass;

import javax.swing.tree.DefaultMutableTreeNode;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: AVK
 * Date: 03.11.13
 * Time: 17:55
 * To change this template use File | Settings | File Templates.
 */
public class MainClass {
    public final static String packageName = "tests";
    public static DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new Data(packageName, false), true);
    static HashMap<String, DefaultMutableTreeNode> linkToTreeNode = new HashMap<String, DefaultMutableTreeNode>();

    public static void main(String[] args) {
        linkToTreeNode.put(packageName, rootNode);
        findClass(packageName);
        Window window = new Window(rootNode);
    }

    static List<Class> classes = new ArrayList<Class>();

    static class TestProcess extends Thread {
        @Override
        public void run() {
            TestNG testNG = new TestNG();
            testNG.setTestClasses(new Class[]{FirstTestClass.class, SecondTestClass.class});
            testNG.run();
        }
    }

    static void findClass(String packageName) {
        URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
        File[] files = new File(root.getFile()).listFiles();
        for (File f : files) {
            if (f.toString().endsWith(".class")) {
                String className = f.getName().replaceAll(".class$", "");
                try {
                    classes.add(Class.forName(packageName + "." + className));
                    Data data = new Data(className, false);
                    DefaultMutableTreeNode node = new DefaultMutableTreeNode(data, false);
                    if (linkToTreeNode.get(packageName) != null)
                        linkToTreeNode.get(packageName).add(node);

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                Data data = new Data(f.getName(), false);
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(data, true);
                String canonical = packageName + "." + f.getName();
                linkToTreeNode.get(packageName).add(node);
                linkToTreeNode.put(canonical, node);
                findClass(canonical);

            }
        }
    }
}
